/*
 DNN Content Builder - sourceforge.net/projects/dnncb
 Copyright (c) 2004-2008
 by Emerson Lopes (emersonlopes@gmail.com)

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
 documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
 the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
 to permit persons to whom the Software is furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all copies or substantial portions 
 of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
 TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
 CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 DEALINGS IN THE SOFTWARE.
*/

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Web;
using System.Web.UI;

namespace DNNContentBuilder.UserControls
{
    /// <summary>
	///		Summary description for FormEngineChildControl
	/// </summary>
	public class FormEngineChildControl : UserControl
	{
		#region Constants
		public const string resource = "~/DesktopModules/DNNContentBuilder/App_LocalResources/FormEngineChildControl";
		public const string SessionKey = "FormEngineChildControlEdit";
		public const string WindowCloseKey = "__close";
		public const string ResultOk = "OK";
		#endregion

		#region Controls
		protected System.Web.UI.WebControls.PlaceHolder plcError;
		protected System.Web.UI.WebControls.PlaceHolder plcFormEngine;
		protected System.Web.UI.WebControls.LinkButton btUpdate;
		protected FormEngine FormEngineInstance;
		#endregion

		#region Properties
		[Bindable(false)]
		[Browsable(false)]
		public string PrimaryKeyValue
		{
			get
			{
				return Request.Params["guid"];
			}
		}

		[Bindable(false)]
		[Browsable(false)]
		public string TableName
		{
			get
			{
				return Request.Params["cbFETable"];
			}
		}

		/// <summary>
		/// Gets the ID of the form definition being displayed.
		/// </summary>
		public int FormDefinitionId
		{
			get 
			{ 
				return FormEngineInstance.FormDefinitionId; 
			}
			set 
			{ 
				FormEngineInstance.FormDefinitionId = value; 
			}
		}

		/// <summary>
		/// Gets the control ID of the caller window used as argument for the 
		/// __doPostBack call.
		/// </summary>
		public string ControlID
		{
			get
			{
				return HttpUtility.UrlDecode(Request.Params["ControlID"]);
			}
		}
		#endregion

		#region Event Handlers
		private void Page_Load(object sender, EventArgs e)
		{
			if (!this.IsPostBack)
			{
				btUpdate.Text = Commons.GetLocalizedString("button_Update", resource);

				if (this.PrimaryKeyValue != null && PrimaryKeyValue.Length > 0)
				{
					DataTable linkedTable = Session[FieldControls.LinkerControl.SessionKey] as DataTable;

					ArgumentValidator.CheckForNullReference(linkedTable, "linkedTable");
					ArgumentValidator.CheckForExpectedType(linkedTable, "linkedTable", typeof(DataTable));

					ArrayList fields = DbContentController.GetFields(this.FormDefinitionId);

				    if (linkedTable != null)
				    {
				        DataRow[] rows = linkedTable.Select(String.Format("{0} = '{1}'", FieldControls.LinkerControl.IDColumnName, this.PrimaryKeyValue));

				        if (rows.Length > 0)
				        {
				            FormEngineInstance.Render(fields, rows[0]);
				        }
				    }
				}
			}
		}

		private void btUpdate_Click(object sender, EventArgs e)
		{
			this.UpdateParentForm();
			this.Close(ResultOk);
		}
		#endregion

		#region Implementation
		/// <summary>
		/// Closes the current window.
		/// </summary>
		protected void Close(string results)
		{
			// TODO: refactor, move to external storage (e.g., resx)
			string windowCloseScript = String.Format(@"
				<script>
					window.opener.__processDialogResults('{0}', ""{1}""); window.close();
				</script>
			", this.ControlID, results.Replace("\"", "\\\""));
            ClientScriptManager cs = Page.ClientScript;
            cs.RegisterStartupScript(this.GetType(), WindowCloseKey, windowCloseScript);
		}

		private void UpdateParentForm()
		{
			Hashtable dictionary = new Hashtable();

			foreach (DictionaryEntry entry in FormEngineInstance.Formlets)
			{
				IFormlet formlet = (IFormlet)entry.Value;

				string entryKey   = (string)entry.Key;
				string entryValue = formlet.GetValue(ContextUtil.GetTypeXml());
				
				dictionary.Add(entryKey, entryValue);
			}

			// If the PK value is null, we are creating a new row
			string primaryKeyValue = this.PrimaryKeyValue != null ? PrimaryKeyValue : Guid.NewGuid().ToString();

			FieldDefinitionList container = new FieldDefinitionList(
				this.FormDefinitionId, primaryKeyValue, this.TableName, dictionary);

			Session.Add(SessionKey, container);
		}
		#endregion

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
			this.btUpdate.Click += new System.EventHandler(this.btUpdate_Click);

		}
		#endregion
	}

	public class FieldDefinitionList
	{
		private readonly int formDefinitionId;
		private readonly string primaryKeyValue;
		private readonly string tableName;
		private readonly Hashtable fieldDictionary;

		public FieldDefinitionList(
			int formDefinitionId, 
			string primaryKeyValue, string tableName, Hashtable fieldDictionary)
		{
			this.formDefinitionId = formDefinitionId;
			this.primaryKeyValue  = primaryKeyValue;
			this.tableName		  = tableName;
			this.fieldDictionary  = fieldDictionary;
		}

		#region Properties
		public int FormDefinitionId
		{
			get
			{
				return this.formDefinitionId;
			}
		}

		public string PrimaryKeyValue
		{
			get
			{
				return this.primaryKeyValue;
			}
		}

		public string TableName
		{
			get
			{
				return this.tableName;
			}
		}

		public Hashtable FieldDictionary
		{
			get
			{
				return this.fieldDictionary;
			}
		}
		#endregion
	}
}
